<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\Parser;
use Parser\Repetition;

class CPIC implements BaseSeparator
{

    public static $ApiKindList = [
        3000 => 'DAMAGELOSSCOVERAGE',
        3002 => 'CARBODYPAINTCOVERAGE',
        4000 => 'THIRDPARTYLIABILITYCOVERAGE',
        4001 => 'THIRDPARTYLEGALHOLIDAYLIMITCLAUSE',
        5001 => 'INCARPASSENGERLIABILITYCOVERAGE',
        5002 => 'INCARDRIVERLIABILITYCOVERAGE',
        40002 => 'THIRDPARTYSPIRITDAMAGELIABILITYCOVERAGE',
        50022 => 'INCARDRIVERSPIRITDAMAGELIABILITYCOVERAGE',
        50012 => 'INCARPASSENGERSPIRITDAMAGELIABILITYCOVERAGE',
    ];

    public function interpreter(array $array, $parser)
    {
        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    public function error(&$array, $parser): bool
    {
        if (($message = $array['message']['code'] ?? false) and ($message != 'success')) {
            $parser->message = $array['message']['message'] ?? $message;
            $parser->code = '500';
            return true;
        }
        return false;
    }

    public function analysis($array): array
    {
        $enquiry = new Enquiry();

        $enquiry->setVCIDiscount($array['result']['commercialInsuransVo']['premiumRatio'] ?? '0');

        $enquiry->setTaxTotal($array['result']['compulsoryInsuransVo']['taxAmount'] ?? '0');
        $enquiry->setTaxPremium($array['result']['compulsoryInsuransVo']['taxAmount'] ?? '0');

        $enquiry->setTCITotal($array['result']['compulsoryInsuransVo']['stCipremium'] ?? '0');
        $enquiry->setTCIPremium($array['result']['compulsoryInsuransVo']['standardPremium'] ?? '0');

        $enquiry->setVCITotal($array['result']['commercialInsuransVo']['premium'] ?? '0');
        $enquiry->setVCIPremium($array['result']['commercialInsuransVo']['standardPremium'] ?? '0');

        //商业险费率因子
        //自主定价系数
        $enquiry->setIndependentPriceRatio($array['result']['commercialInsuransVo']['independentPriceRate'] ?? '');
        //无赔款优待系数NCD
        $enquiry->setNCDRate($array['result']['commercialInsuransVo']['nonClaimDiscountRate'] ?? '0');

        if (isset($array['result']['quoteInsuranceVos'])) {
            foreach ($array['result']['quoteInsuranceVos'] as $kindList) {
                $code = (string)array_search($kindList['insuranceCode'], self::$ApiKindList);
                if (!$code) {
                    continue;
                }
                $coverages['code'] = (string)array_search($kindList['insuranceCode'], self::$ApiKindList);
                $coverages['shortName'] = $kindList['insuranceCode'];
                $coverages['insuredDesc'] = (string)$kindList['amount'] ?? '';
                $coverages['total'] = (string)$kindList['premium'];
                $enquiry->setVCICoverages($coverages);
            }
        }
        if ($repeat = $array['result']['message'] ?? '') {
            if ($array['result']['totalPremium'] ?? false) {
                $enquiry->success();
            } elseif (preg_match('/商业险重复投保/', $repeat)) {
                $enquiry->failure();
                $enquiry->setErrorTip($repeat);
                return $enquiry->get();
            }
        }
        $enquiry->setTotal();
        $enquiry->success();

        return $enquiry->get();
    }

    public function repetition($array): Repetition
    {
        $repetition = new Repetition();

        if (!$message = $array['result']['message'] ?? false) {
            return $repetition;
        }
        if (!preg_match('/商业险重复投保/', $message)) {
            return $repetition;
        }

        if (preg_match('/保单号：(.*)<\/br>/', $message, $policy) and $policy[1] ?? false) {
            $repetition->setLastPolicy($policy[1]);
        }

        if (preg_match('/签单日期：(.*)<\/br>/', $message, $lastSignTime) and $lastSignTime[1] ?? false) {
            $lastSignTime = date('Y-m-d H:i:s', strtotime(str_replace(['年', '月', '日', '时', '分'], [
                '-',
                '-',
                '',
                ':',
                '',
            ], $lastSignTime[1])));
            $repetition->setLastSignTime($lastSignTime);
        }

        if (preg_match('/起保日期：(.*)<\/br>/', $message, $startAt) and $startAt[1] ?? false) {
            $startAt = date('Y-m-d H:i:s', strtotime(str_replace(['年', '月', '日', '时', '分'], [
                '-',
                '-',
                '',
                ':',
                '',
            ], $startAt[1])));

            $repetition->setLastStartAt($startAt);
        }

        if (preg_match('/终保日期：(.*)<\/br>/', $message, $endAt) and $endAt[1] ?? false) {
            $endAt = date('Y-m-d H:i:s', strtotime(str_replace(['年', '月', '日', '时', '分'], [
                '-',
                '-',
                '',
                ':',
                '',
            ], $endAt[1])));
            $repetition->setLastEndTime($endAt);
        }

        if (preg_match('/车牌号：(.*)<\/br>/', $message, $license) and $license[1] ?? false) {
            $repetition->setLicense($license[1]);
        }

        if (preg_match('/重复投保的保险公司：(.*)<\/br>/', $message, $lastCompany) and $lastCompany[1] ?? false) {
            $repetition->setLastCompany($lastCompany[1]);
        }

        if (preg_match('/已投保子险为：(.*)<\/br><\/br><\/br>/', $message, $coverage) and $coverage[1] ?? false) {
            $coverage = $coverage[1];
            $coverage = explode('</br>', $coverage);

            $repetition->setLastCoverage($coverage);;
        }

        if ($repetition->getLastCompany()) {
            $repetition->setStatus('success');
        }
        return $repetition;
    }
}
